package com.zy.servlet.car;

import com.zy.service.AddToCarService;
import com.zy.service.impl.AddToCarServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addToCar")
public class AddToCarServlet extends HttpServlet {
    private AddToCarService addToCarService = new AddToCarServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.getSession().getAttribute("loggedIn") == null) {
            resp.sendRedirect("login.jsp");
            return;
        }
        System.out.println("AddToCarServlet");
        System.out.println("Session User ID: " + req.getSession().getAttribute("userId"));
        Integer userId = (Integer) req.getSession().getAttribute("userId");
        String shopIdParam = req.getParameter("shopId");
        if (userId == null || shopIdParam == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid user or shop ID");
            return;
        }

        int shopId = Integer.parseInt(shopIdParam);
        System.out.println("User ID: " + userId);
        System.out.println("Shop ID: " + shopIdParam);
        boolean success = addToCarService.addToCar(userId, shopId);

        if (success) {
            resp.setContentType("application/json");
            resp.getWriter().write("{\"success\": true}");
        } else {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to add item to cart");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
